import React from 'react';
import { connect } from 'dva';
import { Layout, Button, Table, Divider, Input, message, Row, Col, Pagination} from 'antd';
import { Form } from '@ant-design/compatible';
import moment from 'moment'
import BaseComponent from 'components/BaseComponent';
import './index.less';
const { Content } = Layout;
import { getCoursewareList, delCourseware } from '../service'
import $$ from 'cmn-utils'

const createForm = Form.create;
@connect(({ courseware }) => ({
  courseware
}))
class CoursewareManage extends BaseComponent {
  constructor (props) {
    super(props)

    this.state = {
      currentPage: 1,
      pageSize: 10,
      coursewareList: {}
    }
  }

  componentWillMount () {
    this.getList()
  }

  handleSubmit = (e) => {
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.getList(values)
      }
    })
  }

  getList = (value) => {
    if(!value) {
      value = {}
    }
    value.pageSize = value.pageSize || this.state.pageSize
    value.pageNumber = value.pageNumber || this.state.currentPage
    getCoursewareList(value).then(resp => {
      if (resp && resp.data && resp.status) {
        this.setState({
          coursewareList: resp.data
        })
      } else {
        message.error('获取课件列表失败')
      }
    }).catch(err => {
      console.log('获取课件列表失败:', err)
    })
  }

  onChangeType = (val) => {
    const type = val.type
    if (val.text && type == 'edit' || type == 'show') {
      $$.setStore('id', val.text.id)
    }

    const { dispatch } = this.props;
    dispatch({
      type: 'courseware/changeType',
      payload: type
    });
  }

  onDelete = (val) => {
    delCourseware(val).then(resp => {
      if (resp && resp.status) {
        message.success('删除课件成功')
        this.getList({pageNumber: 1})
      } else {
        message.error('删除课件失败')
      }
    }).catch(err => {
      console.log('删除课件失败:', err)
    })
  }

  onDownload = (url) => {
    window.location.href=url
  }

  // 每页条数改变
  handleShowSizeChange = (_, pageSize) => {
    this.setState({
      currentPage: 1,
      pageSize: pageSize
    }, () => { this.getList() })
  }

  // 页码改变
  handlePageChange = (current, pageSize) => {
    this.setState({
      currentPage: current
    }, () => { this.getList() })
  }

  render() {
    const { coursewareList, currentPage, pageSize } = this.state

    const columns = [
      {
        title: '课件名称',
        dataIndex: 'name',
        key: 'name',
        width: 100
      },
      {
        title: '创建时间',
        key: 'createTime',
        width: 80,
        render: text => <span>{moment(text.createTime).format('YYYY-MM-DD HH:mm:ss')}</span>
      },
      {
        title: '修改时间',
        key: 'updateTime',
        width: 80,
        render: text => <span>{moment(text.updateTime).format('YYYY-MM-DD HH:mm:ss')}</span>
      },
      {
        title: '操作',
        key: 'id',
        width: 40,
        align: 'center',
        render: text => {
          return (
            <div>
              <a onClick={this.onChangeType.bind(this, {type: 'show', text})}>查看</a>
              <Divider type='vertical' />
              <a onClick={this.onChangeType.bind(this, {type: 'edit', text})}>修改</a>
              <Divider type='vertical' />
              <a onClick={this.onDownload.bind(this, text.url)}>下载</a>
              <Divider type='vertical' />
              <a onClick={this.onDelete.bind(this, text.id)}>删除</a>
            </div>
          )
        }
      }
    ]

    const { form } = this.props
    const { getFieldDecorator } = form
    return (
      <Layout className="full-layout page coursewareManage-page">
        <Content>
          <Form layout='inline' style={{paddingBottom: '25px'}} onSubmit={this.handleSubmit}>
            <Row>
              <Col span={4}>
                <Form.Item>
                  {getFieldDecorator('name')(<Input placeholder='课件名称' />) }
                </Form.Item>
              </Col>
              <Col span={18}>
                <Form.Item>
                  <Button type='primary' htmlType='submit'>
                        查询
                  </Button>
                </Form.Item>
              </Col>
              <Col span={2}>
                <Button type='primary' style={{float: 'right'}} onClick={this.onChangeType.bind(this, {type: 'add'})}>
                  新建课件
                </Button>
              </Col>
            </Row>
          </Form>

          

          <Table
            columns={columns}
            pagination={false}
            dataSource={coursewareList.list}
            onChange={this.handleTableChange}
            rowKey='id'
          />
          <Pagination
            size='small'
            disabled={coursewareList.total === 0}
            showSizeChanger
            pageSizeOptions={['2', '10', '20', '30', '50', '100']}
            total={coursewareList.total}
            current={currentPage}
            pageSize={pageSize}
            onShowSizeChange={this.handleShowSizeChange}
            onChange={this.handlePageChange}
            showTotal={() => `共 ${coursewareList.total} 条`}
            style={{ marginTop: '10px' }}
          />
        </Content>
      </Layout>
    );
  }
}

export default createForm()(CoursewareManage);
